package com.ruoyi.sjfx.zlsqfx.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.sjfx.zlsqfx.service.lZlsqfxService;
import com.ruoyi.sjfx.zlsqfx.vo.ZlsqfxVo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/sjfx/zlsqfx")
public class ZlsqfxController extends BaseController {

    /**
     * 专利授权分析
     */
    @Resource
    private lZlsqfxService zlsqfxService;

    @GetMapping(value = "/selectZlsqfxList")
    public AjaxResult selectZlsqfxList(ZlsqfxVo zlsqfxVo) {

        List<ZlsqfxVo> zlsqfxVos = zlsqfxService.selectZlsqfxList();
        // 提取年份并去重
        String[] yearsArray = zlsqfxVos.stream()
                .map(ZlsqfxVo::getNd) // 假设getNd()方法可以获取'nd'字段值
                .distinct()           // 去重
                .sorted()             // 可选：排序年份
                .toArray(String[]::new);

        LinkedHashMap<String, Integer> fmzlCounts = getGfByCounts("发明专利");
        LinkedHashMap<String, Integer> wgzlCounts = getGfByCounts("外观专利");
        LinkedHashMap<String, Integer> syzlCounts = getGfByCounts("实用专利");

        int[] fmZlCountsArray = encapsulateValuesToPrimitiveArray(fmzlCounts);
        int[] wgZlCountsArray = encapsulateValuesToPrimitiveArray(wgzlCounts);
        int[] syZlCountsArray = encapsulateValuesToPrimitiveArray(syzlCounts);

        // 使用 Map 封装数据
        Map<String, Object> result = new HashMap<>();
        result.put("yearsArray", yearsArray);
        result.put("fmZlCountsArray", fmZlCountsArray);
        result.put("wgZlCountsArray", wgZlCountsArray);
        result.put("syZlCountsArray", syZlCountsArray);


        return AjaxResult.success(result);
    }
    private LinkedHashMap<String, Integer> getGfByCounts(String zllx) {

        List<ZlsqfxVo> zlsqfxVo = zlsqfxService.selectZlsqfxList();

        return zlsqfxVo.stream()
                .filter(item -> zllx.equals(item.getZllx()))
                .collect(Collectors.groupingBy(
                        ZlsqfxVo::getNd,
                        TreeMap::new, // 使用TreeMap自动按键排序
                        Collectors.summingInt(ZlsqfxVo::getSl)
                ))
                .entrySet().stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (e1, e2) -> e1,
                        LinkedHashMap::new // 转换为LinkedHashMap以保留排序结果
                ));
    }
    public int[] encapsulateValuesToPrimitiveArray(LinkedHashMap<String, Integer> counts) {
        return counts.values().stream().mapToInt(Integer::intValue).toArray();
    }
}
